<?php

namespace App\Http\Controllers\UI;

use App\Http\Controllers\Controller;
use App\Miya\Models\Area;
use App\Miya\Models\Classify;
use App\Miya\Models\Info;
use App\Miya\Models\Module;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;

class SitemapController extends Controller
{
    public function index()
    {
        $sitemap = App::make('sitemap');

        $sitemap->setCache('laravel.sitemap', 60);

        if (!$sitemap->isCached()) {
            $sitemap->add(URL::to('/'), now(), '1.0', 'daily');

            $modules = Module::all();
            foreach ($modules as $module) {
                $sitemap->add(route('pc.classify', [$module->tag]), $module->updated_at, '1.0', 'daily');
                $sitemap->add(route('m.classify', [$module->tag]), $module->updated_at, '1.0', 'daily');
            }

            $classifies = Classify::with(['module'])->get();
            foreach ($classifies as $classify) {
                $sitemap->add(route('pc.classify', [$classify->module->tag, $classify->tag]), $classify->updated_at, '1.0', 'daily');
                $sitemap->add(route('m.classify', [$classify->module->tag, $classify->tag]), $classify->updated_at, '1.0', 'daily');
            }

            $infos = Info::whereHas('classify')->with(['module', 'classify'])->get();
            foreach ($infos as $info) {
                $sitemap->add(route('pc.info', [$info->module->tag, $info->classify->tag, $info->tag]), $info->updated_at, '1.0', 'daily');
                $sitemap->add(route('m.info', [$info->module->tag, $info->classify->tag, $info->tag]), $info->updated_at, '1.0', 'daily');
            }

            $areas = Area::all();
            foreach ($areas as $area) {
                $sitemap->add(route('area.index', $area->tag), now(), '1.0', 'daily');
                if (config('setting.open_domain_area_route') == 1) {
                    $sitemap->add(route('domain_area.index', $area->tag), now(), '1.0', 'daily');
                }
            }
        }

        return $sitemap->render('html');
    }
}
